package com.qingshu.common.util.thread;

import com.qingshu.common.util.spring.SpringUtils;

import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 异步任务管理
 *
 * @author Huzz
 * @created 2021-12-08 18:12
 */
public class TaskAsync {

    /**
     * 实例化自身(单例模式)
     */
    private static TaskAsync instance = new TaskAsync();

    /**
     * 操作延迟10毫秒
     */
    private final int OPERATE_DELAY_TIME = 10;

    /**
     * 异步操作任务调度线程池
     */
    private ScheduledExecutorService executor = SpringUtils.getBean("scheduledExecutorService");

    /**
     * 执行任务
     * @param task
     */
    public static void executeTask(TimerTask task) {
        instance.execute(task);
    }

    /**
     * 执行任务
     * @param task
     */
    private void execute(TimerTask task) {
        executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
    }

    /**
     * 停止任务线程池
     */
    public static void shutDownPool(){
        instance.shutdown();
    }

    /**
     * 停止任务线程池
     */
    private void shutdown()
    {
        Threads.shutdownAndAwaitTermination(executor);
    }


}
